package com.googlecode.perfectable.visuable.renderer.xml;

import static com.google.common.base.Preconditions.checkNotNull;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import com.googlecode.perfectable.visuable.renderer.ElementRenderer;
import com.googlecode.perfectable.visuable.renderer.VisualRenderer;

public class XmlElementRenderer implements ElementRenderer {
	private final XMLStreamWriter xmlWriter;

	public XmlElementRenderer(XMLStreamWriter xmlWriter, String elementName) {
		this.xmlWriter = checkNotNull(xmlWriter);
		try {
			this.xmlWriter.writeStartElement(elementName);
		}
		catch(XMLStreamException e) {
			throw new RuntimeException(e); // TODO Auto-generated catch block
		}
	}

	@Override
	public void raw(String data) {
		try {
			this.xmlWriter.writeCharacters(data);
		}
		catch(XMLStreamException e) {
			throw new RuntimeException(e); // TODO Auto-generated catch block
		}
	}

	@Override
	public void attribute(String name, String value) {
		try {
			this.xmlWriter.writeAttribute(name, value);
		}
		catch(XMLStreamException e) {
			throw new RuntimeException(e); // TODO Auto-generated catch block
		}
	}

	@Override
	public VisualRenderer children() {
		return new XmlVisualRenderer(this.xmlWriter);
	}

	@Override
	public void close() {
		try {
			this.xmlWriter.writeEndElement();
		}
		catch(XMLStreamException e) {
			throw new RuntimeException(e); // TODO Auto-generated catch block
		}
	}
}
